package com.liuqing.www.多线程技术;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class Client2 {
	Socket socket = null;
	DataInputStream dis = null;
	DataOutputStream dos = null;
	Thread receive = new Thread(new ReceiveThread());

	public Client2(String str) {
		try {
			socket = new Socket("127.0.0.1", 8888);
			dis = new DataInputStream(socket.getInputStream());
			dos = new DataOutputStream(socket.getOutputStream());
			send_data(str);
			receive.start();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void send_data(String str) {

		try {
			dos.write(str.getBytes());
			dos.flush();
			dos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public class ReceiveThread implements Runnable {

		public void run() {
			String str = "";
			StringBuffer sBuffer = new StringBuffer();
			char[] buf = new char[10];
			try {
				BufferedReader inBufferedReader = new BufferedReader(
						new InputStreamReader(socket.getInputStream()));
				if (inBufferedReader.read() != -1) {
					while (true) {
						sBuffer.delete(0, buf.length);
						sBuffer.append(buf, 0, buf.length);
						str = new String(sBuffer.toString().trim().getBytes(
								"utf8"), "utf8");
						System.out.println("读取：" + str);
//						MsgReturn.setMesgReturn(str);
						sBuffer.delete(0, buf.length);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
}